﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MT.Enterprise.Utils.Extensions;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Engine;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.CourseTrain;
using NP.BPMReportPlatform.CourseTrain.Dtos;

using NP.BPMReportPlatform.Utils;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using NP.Enterprise.Utils.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NP.BPMReportPlatform.UserTrial.Dto;
using NP.BPMReportPlatform.Common.Dtos;
using Microsoft.EntityFrameworkCore;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Elasticsearch.Net;
using NP.BPMReportPlatform.Document.Dtos;
using NP.BPMReportPlatform.Document;
using RestSharp;
using NP.BPMReportPlatform.Contract.Dtos;

namespace NP.BPMReportPlatform.CourseTrain
{
    /// <summary>
    /// 试用期服务
    /// </summary>
    public class DocumentService : BPMReportPlatformAppService, IDocumentService
    {
        #region Variables

        private readonly string _uploadUrl;
        private string _downLoadUrl;
        #endregion

        #region Constructor

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sqlSugarAppService"></param>
        public DocumentService(IConfiguration configuration)
        {
            _uploadUrl = configuration["BPM:AttachmentUpLoadUrl"];
            _downLoadUrl = configuration["BPM:AttachmentDownLoadUrl"];
        }

        #endregion


        #region 文件上传和下载

        /// <summary>
        /// 上传文件到BPM系统
        /// </summary>
        /// <param name="bytes">文件byte</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public async Task<(bool Result, string Msg)> Upload(byte[] bytes, string fileName)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.Timeout = TimeSpan.FromSeconds(30);
                using (var postContent = new MultipartFormDataContent())
                {
                    string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
                    string userInfo = "{\"id\":\"" + CurrentUser.Id + "\",\"name\":\"" + CurrentUser.Name + "\",\"account\":\"" + CurrentUser.Id + "\",\"language\":\"zh\"}";
                    postContent.Headers.Add("current_user", Convert.ToBase64String(Encoding.UTF8.GetBytes(userInfo)));
                    postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
                    postContent.Add(new ByteArrayContent(bytes), "files", fileName);
                    try
                    {
                        Uri uri = new Uri(_uploadUrl);
                        var response = await httpClient.PostAsync(uri, postContent);
                        string msg = await response.Content.ReadAsStringAsync();
                        return (response.IsSuccessStatusCode, msg);
                    }
                    catch (Exception ex)
                    {
                        return (false, ex.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 从BPM系统下载附件
        /// </summary>
        /// <param name="documentId">附件ID</param>
        /// <returns></returns>
        public Task<byte[]> DownLoad(string documentId)
        {
            if (documentId.IsNullOrEmpty())
            {
                throw new Exception("无效请求");
            }

            RestClient client = new RestClient();
            string url = string.Format(_downLoadUrl, documentId);
            var result = client.DownloadData(new RestRequest(url, Method.GET));

            return Task.FromResult(result);
        }

        /// <summary>
        /// 下载海外培训培训总结模板
        /// </summary>
        /// <returns></returns>
        public FileStream DownOverSeaSummaryTemplete()
        {
            return File.OpenRead(Environment.CurrentDirectory + "/wwwroot/ppt/海外培训报告模板.pptx");
        }
        #endregion
    }
}